/**
 * MongoDB 模块配置
 * 用于存储埋点日志和上传内容
 */

import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { TrackingLog, TrackingLogSchema } from './schemas/tracking-log.schema';
import { TrackingUpload, TrackingUploadSchema } from './schemas/tracking-upload.schema';
import { Website, WebsiteSchema } from './schemas/website.schema';
import { PageView, PageViewSchema } from './schemas/page-view.schema';

@Module({
  imports: [
    MongooseModule.forRootAsync({
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: (configService: ConfigService) => {
        const mongoHost = configService.get<string>('MONGO_HOST') || 'localhost';
        const mongoPort = configService.get<number>('MONGO_PORT') || 27017;
        const mongoDatabase = configService.get<string>('MONGO_DATABASE') || 'tracker';
        const mongoUsername = configService.get<string>('MONGO_USERNAME') || 'tracker';
        const mongoPassword = configService.get<string>('MONGO_PASSWORD') || '';
        
        // 构建 MongoDB 连接字符串
        let mongoUri: string;
        if (mongoUsername && mongoPassword) {
          // 尝试不同的认证数据库
          mongoUri = `mongodb://${mongoUsername}:${encodeURIComponent(mongoPassword)}@${mongoHost}:${mongoPort}/${mongoDatabase}?authSource=${mongoDatabase}`;
        } else {
          mongoUri = `mongodb://${mongoHost}:${mongoPort}/${mongoDatabase}`;
        }

        console.log('MongoDB connection config:', {
          host: mongoHost,
          port: mongoPort,
          database: mongoDatabase,
          username: mongoUsername,
          password: '******',
        });

        return {
          uri: mongoUri,
          retryWrites: true,
          w: 'majority',
        };
      },
    }),
    MongooseModule.forFeature([
      { name: TrackingLog.name, schema: TrackingLogSchema },
      { name: TrackingUpload.name, schema: TrackingUploadSchema },
      { name: Website.name, schema: WebsiteSchema },
      { name: PageView.name, schema: PageViewSchema },
    ]),
  ],
  exports: [MongooseModule],
})
export class TrackingMongoModule {}

